//
//  MarkaCell.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/1/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

final class MarkaCell: UITableViewCell {
    
    // MARK: - UI
    
    private lazy var iconView: UIImageView = {
        let img = UIImageView()
        img.contentMode = .scaleAspectFit
        return img
    }()
    private lazy var titleLabel: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        lbl.numberOfLines = 1
        lbl.textColor = .black
        return lbl
    }()
    private lazy var arrowBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "arrow"), for: .normal)
        return btn
    }()
    
    // MARK: - Props
    
    var marka: Marka! {
        didSet {
            self.titleLabel.text = marka.name_ru
            if let logoUrl = marka.logo {
                self.iconView.sd_setImage(with: URL(string: logoUrl)!)
                self.iconView.image?.sd_tintedImage(with: .darkBlueColor)
            }
        }
    }
    
    // MARK: - Actions
    
    @objc func onArrowClick (sender: UIButton) {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "showModels"), object: nil, userInfo: ["marka": marka as Any, "icon": iconView.image as Any])
    }
    
    // MARK: - Init
   
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.setUpView()
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        self.iconView.image = nil
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func getIcon () -> UIImage? {
        return iconView.image
    }
    
}


// MARK: - Configuring UI

extension MarkaCell {
    fileprivate func setUpView() {
        self.contentView.addSubview(iconView)
        self.contentView.addSubview(titleLabel)
        self.contentView.addSubview(arrowBtn)
        self.addConstraints()
        self.arrowBtn.addTarget(self, action: #selector(onArrowClick(sender:)), for: .touchUpInside)
    }
    
    fileprivate func addConstraints () {
        iconView.snp.makeConstraints { (make) in
            make.width.height.equalTo(20)
            make.leading.equalTo(16)
            make.centerY.equalToSuperview()
        }
        arrowBtn.snp.makeConstraints { (make) in
            make.width.equalTo(8)
            make.height.equalTo(13)
            make.trailing.equalToSuperview().inset(16)
            make.centerY.equalToSuperview()
        }
        titleLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.leading.equalTo(iconView.snp.trailing).offset(12)
            make.trailing.equalTo(arrowBtn.snp.leading).inset(12)
        }
    }
}



